package com.yunduo.module.FileStore.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.yunduo.entity.vo.FileObj;
import com.yunduo.module.FileStore.FileStore;
import com.yunduo.module.pool.OSSPool;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * 文件存储阿里云
 */
public class OssStore implements FileStore {
    @Resource
    private OSSPool ossPool;

    //上传文件 返回访问路径
    public String upLoadFile(FileObj file){
        OSS ossClient = ossPool.getConnection();
        InputStream is = new ByteArrayInputStream(file.getData());
        ossClient.putObject(ossPool.getBucketName(), file.getType().getEName()+"/"+file.getName(), is);
        ossPool.addConnection(ossClient);
        return getFileUrl(file);
    }
    //下载文件
    public InputStream downloadFile(FileObj file){
        OSS ossClient = ossPool.getConnection();
        OSSObject ossObject = ossClient.getObject(ossPool.getBucketName(), file.getType().getEName()+"/"+file.getName());
        InputStream inputStream = ossObject.getObjectContent();
        ossPool.addConnection(ossClient);
        return inputStream;
    }
    //删除文件
    public boolean deleteFile(FileObj file){
        OSS ossClient = ossPool.getConnection();
        ossClient.deleteObject(ossPool.getBucketName(), file.getType().getEName()+"/"+file.getName());
        ossPool.addConnection(ossClient);
        return true;
    }
    //获取url
    private String getFileUrl(FileObj file){
        String endpoint = ossPool.getEndpoint().substring(7);
        return "https://"+ossPool.getBucketName()+"."+endpoint+"/"+file.getType().getEName()+"/"+file.getName();
    }
}
